﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;


namespace mojoPortal.Web.RS.SBM
{
    public partial class RSShoppingPart : RSBasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage("Inventory");
                RSUserIdentity userIdentity = GetRSUserIdentity();
                int companyid = userIdentity.RSCompanyId;
                int WorkOrderid = 0;
                int Estimateid = 0;
                if (Request.QueryString["workorderid"] != null)
                {
                    WorkOrderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
                    LoadInventoryListFilterByWorkOrderID(companyid, WorkOrderid);
                }
                if (Request.QueryString["Estimateid"] != null)
                {
                    Estimateid = Convert.ToInt32(Request.QueryString["Estimateid"].ToString());
                    LoadInventoryListFilterByEstimateID(companyid, Estimateid);
                }

                if (WorkOrderid == 0 && Estimateid == 0)
                {
                    LoadInventoryList(companyid);
                }

                ucShoppingPartListControl.Visible = false;
                RSSBMDataLookupLoader.LoadInventoryCategoryDDL(companyid, ddlInventoryCategory);
            }
        }

        protected void gvInventoryItem_Edit(object sender, CommandEventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int companyid = userIdentity.RSCompanyId;
            int productid = Convert.ToInt32(e.CommandArgument.ToString());
            if (companyid > 0 && productid > 0)
                ucModalProductControl.ShowModal(companyid, productid, false);
        }

        protected void btnReturn_Click(Object sender, EventArgs e)
        {
            int WorkOrderid = 0;
            if(Request.QueryString["workorderid"] != null)
                WorkOrderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
            
            int Estimateid = 0;
            if (Request.QueryString["Estimateid"] != null)
                Estimateid = Convert.ToInt32(Request.QueryString["Estimateid"].ToString());

            if (Request.QueryString["isEstimate"] == "1")
                Response.Redirect("~/RS/SBM/RSEstimateParts.aspx?&Estimateid=" + Estimateid);
            else
                Response.Redirect("~/RS/SBM/RSWorkOrderParts.aspx?&workorderid=" + WorkOrderid);
        }
        private void ViewShoppingPart()
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int companyid = userIdentity.RSCompanyId;
            ucShoppingPartListControl.ShowShoppingPartList(companyid);
            ucShoppingPartListControl.Visible = true;
        }
        protected void btnAddPart_OnClick(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                TextBox txtQty = gvInventoryList.SelectedRow.FindControl("txtQuantity") as TextBox;
                
                if (txtQty != null && txtQty.Text.Length > 0 && RSSBMCommonFunctions.IsNumeric(txtQty.Text) == true)
                {
                    int qty = Convert.ToInt32(txtQty.Text);
                    int productid = Convert.ToInt32(gvInventoryList.SelectedValue.ToString());
                    List<ShoppingPart> selParts = new List<ShoppingPart>();
                    if (Session["SHOPPING_PARTLIST"] != null)
                        selParts = (List<ShoppingPart>)Session["SHOPPING_PARTLIST"];
                    //Remove any duplicate
                    if (selParts.Count > 0)
                    {
                        for (int i = 0; i < selParts.Count; i++)
                        {
                            if (selParts[i].ProductId == productid)
                            {
                                selParts.RemoveAt(i);
                                break;
                            }
                        }
                    }
                    txtQty.Text = "";
                    selParts.Add(new ShoppingPart(productid, qty, "", 0, 0, ""));
                    Session["SHOPPING_PARTLIST"] = selParts;
                    SetSelectedRowState(false);
                    gvInventoryList.SelectedIndex = -1;

                }
                ViewShoppingPart();
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);

            
        }
        private void SetSelectedRowState(bool bstate)
        {
            if (gvInventoryList.SelectedIndex >= 0)
            {
                TextBox txtQty = gvInventoryList.SelectedRow.FindControl("txtQuantity") as TextBox;
                if (txtQty != null)
                {
                    txtQty.Enabled = bstate;
                    if (bstate == false)
                        txtQty.BackColor = System.Drawing.Color.Gainsboro;
                    else
                        txtQty.BackColor = System.Drawing.Color.White;

                }
                Button btnAdd = gvInventoryList.SelectedRow.FindControl("btnAddPart") as Button;
                if (btnAdd != null)
                    btnAdd.Visible = bstate;
            }
        }
        protected void gvInventoryList_SelectedIndexChanging(Object sender, EventArgs e)
        {
            SetSelectedRowState(false);
        }
        protected void gvInventoryList_SelectedIndexChanged(Object sender, EventArgs e)
        {
            SetSelectedRowState(true);
        }
        public void LoadInventoryListFilterByEstimateID(int companyid, int Estimateid)
        {
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            String sqlSELECT = "SELECT c.ProductId,c.ProductName,c.QuantityPerUnit,c.UnitPrice,c.UnitsInStock,c.UnitsOnOrder, c.ReorderLevel,c.ProductDesc," +
                                "c.Manufacture,c.Discontinued,c.ModelNo,c.ProductCode,c.ParentId, (SELECT p.ProductName FROM rs_tblInventory p WHERE p.ProductId=c.ParentId) as CategoryName,c.SupplierID,c.CompanyId " +
                                " FROM rs_tblInventory c WHERE c.IsEquipment=0 AND c.companyid=@companyid AND c.ParentId > 0 AND c.ProductId NOT IN(SELECT o.ProductId FROM rs_tblEstimatePart o WHERE o.EstimateId=@EstimateId)  order by CategoryName ";

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@Estimateid";
            param.Value = Estimateid;
            myCommand.Parameters.Add(param);

            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);

            gvInventoryList.DataSource = ds;
            gvInventoryList.DataBind();
            myConnection.Close();
        }
        public void LoadInventoryListFilterByWorkOrderID(int companyid, int WorkOrderid)
        {
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            String sqlSELECT = "SELECT c.ProductId,c.ProductName,c.QuantityPerUnit,c.UnitPrice,c.UnitsInStock,c.UnitsOnOrder, c.ReorderLevel,c.ProductDesc," +
                                "c.Manufacture,c.Discontinued,c.ModelNo,c.ProductCode,c.ParentId, (SELECT p.ProductName FROM rs_tblInventory p WHERE p.ProductId=c.ParentId) as CategoryName,c.SupplierID,c.CompanyId " +
                                " FROM rs_tblInventory c WHERE c.IsEquipment=0 AND c.companyid=@companyid AND c.ParentId > 0 AND c.ProductId NOT IN(SELECT o.ProductId FROM rs_tblWorkOrderPart o WHERE o.workorderid=@WorkOrderId)  order by CategoryName ";

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@WorkOrderid";
            param.Value = WorkOrderid;
            myCommand.Parameters.Add(param);

            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);

            gvInventoryList.DataSource = ds;
            gvInventoryList.DataBind();
            myConnection.Close();
        }
        public void LoadInventoryList(int companyid)
        {
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            String sqlSELECT = "SELECT c.ProductId,c.ProductName,c.QuantityPerUnit,c.UnitPrice,c.UnitsInStock,c.UnitsOnOrder, c.ReorderLevel,c.ProductDesc," +
                                "c.Manufacture,c.Discontinued,c.ModelNo,c.ProductCode,c.ParentId, (SELECT p.ProductName FROM rs_tblInventory p WHERE p.ProductId=c.ParentId) as CategoryName,c.SupplierID,c.CompanyId " +
                                " FROM rs_tblInventory c WHERE c.IsEquipment=0 AND c.companyid=@companyid AND c.ParentId > 0 order by CategoryName ";

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
            myConnection.Open();
            DataSet ds = new DataSet();
            adapter.Fill(ds);

            gvInventoryList.DataSource = ds;
            gvInventoryList.DataBind();
            myConnection.Close();
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }
            return newSortDirection;
        }

        protected void gvInventoryList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvInventoryList.PageIndex = e.NewPageIndex;
            gvInventoryList.DataBind();
        }

        protected void gvInventoryList_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dataTable = Session["DATATABLE"] as DataTable;
            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                gvInventoryList.DataSource = dataView;
                gvInventoryList.DataBind();
            }
        }
    }
}


